﻿#include "hzpch.h"
#include "Hazel.h"
#include "Renderer/Renderer.h"

#include "Log.h"

int HazelInit()
{
    HZ_INFO("Hazel Engine Initialized!");
    return 0;
}

namespace Hazel
{
    // 或写成 {}
    Application::Application() : m_Window(nullptr), m_Running(true) // 可先设为 nullptr，第三阶段再创建
    {
        // 1. 创建窗口（会初始化 GLFW 并创建 OpenGL 上下文）
        m_Window.reset(Window::Create()); // reset 接受原始指针

        m_Window->SetEventCallback(HZ_BIND_EVENT_FN(Application::OnEvent));
        // 必须初始化 Renderer
        Renderer::Init();
        HZ_INFO("Application Created!");
    }

    Application::~Application()
    {
        Renderer::Shutdown(); // 可选：清理
        HZ_INFO("Application Destroyed!");
    }

    void Application::PushLayer(Layer *layer)
    {
        m_LayerStack.PushLayer(layer);
    }

    void Application::PushOverlay(Layer *overlay)
    {
        m_LayerStack.PushOverlay(overlay);
    }

    void Application::Run()
    {
        HZ_INFO("Application Running!");
        while (m_Running)
        {
            // 更新所有 Layer
            for (Layer *layer : m_LayerStack)
                layer->OnUpdate();

            // 手动测试事件
            static int frame = 0;
            if (frame++ % 100 == 0)
            {
                Hazel::WindowCloseEvent e;
                OnEvent(e);
            }
        }
    }
    void Application::OnEvent(Event &e)
    {
        if (e.GetEventType() == EventType::WindowClose)
        {
            HZ_INFO("WindowClose event received. Shutting down...");
            m_Running = false;
        }

        // 后续可加入 LayerStack 分发
        // 事件从顶层向下传递（逆序）
        for (auto it = m_LayerStack.end(); it != m_LayerStack.begin();)
        {
            (*--it)->OnEvent(e);
            if (e.Handled)
                break;
        }
    }
    bool Application::OnWindowClose(WindowCloseEvent &e)
    {
        m_Running = false;
        return true;
    }
    bool Application::OnWindowResize(WindowResizeEvent &e)
    {
        // TODO: 调用 GLViewport
        return false;
    }
    // 全局函数（供 Sandbox 调用）
    // Hazel::Application *Hazel::CreateApplication()
    // {
    //     return new Hazel::Application();
    // }

}